import getUserTempId from '@/utils/userTempId'
import {requestLogin,requestUserInfo,requestLogout} from '@/api'

const state = {
    userTempId: getUserTempId(),
    token:localStorage.getItem("user_Token") || "",
    nickName:''
}
const mutations = {
    SET_TOKEN_STATE(state,value){
        state.token = value
    },
    SET_NICKNAME_STATE(state,value){
        state.nickName = value
    },
    SET_LOGOUT_STATE(state) {
        state.token = "";
        state.nickName = "";
        localStorage.removeItem("user_Token");
    },
}
const actions = {
    async getLogin({commit},userInfo){
       const re = await requestLogin(userInfo)
       commit('SET_TOKEN_STATE',re.token)
       //请求到token之后,要把token持久化到本地中,否则刷新以后vuex就没有数据了,用户需要重新登录
        localStorage.setItem("user_Token", re.token);
    },
    async getUserInfo({commit}){
        try {
            const re = await requestUserInfo()
            commit('SET_NICKNAME_STATE',re.nickName)
        } catch (e) {
            //在使用token发送请求的时候,如果token过期,则会抛出错误,被这里接受,我们可以清除掉token
            localStorage.removeItem("user_Token");
            //如果这里请求报错,则返回一个失败的promise实例,则dispatch方法就会返回这个失败的实例
            return Promise.reject();
        }
        
     },
      //退出登录
    async getLogout({ commit }) {
        await requestLogout();
        commit("SET_LOGOUT_STATE");
    },
}
const getters = {}

export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}